package org.example;

/**
 * 单链表反转, 头插法实现
 */
public class ReverseListSolution {

    public static void main(String[] args) {
        ReverseListSolution solution = new ReverseListSolution();
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        ListNode listNode = solution.ReverseList(head);
        System.out.println(listNode);
    }

    public ListNode ReverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode resultNode = null;
        ListNode tempNode = head;
        ListNode nextNode = head.next;
        head.next = null;
        do {
            if (resultNode == null) {
                resultNode = tempNode;
            } else {
                ListNode temp = resultNode;
                resultNode = tempNode;
                tempNode.next = temp;
            }
            tempNode = nextNode;
            if (tempNode != null) {
                nextNode = tempNode.next;
                tempNode.next = null;
            }
        } while (tempNode != null);
        return resultNode;
    }

    public static class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }
}
